package com.crazy.common.form;

import static org.springframework.security.core.context.SecurityContextHolder.getContext;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.crazy.entity.sys.PubSysLog;
import com.crazy.entity.sys.PubUser;
import com.crazy.service.sys.PubSysLogService;

/**
 * 系统日志处理拦截器
 * 
 * @author admin
 */
public class SysLogHandlerInterceptor extends HandlerInterceptorAdapter {
	private long processTime;
	@Inject
	private PubSysLogService service;
	private PubSysLog sysLog = new PubSysLog();

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if (handler instanceof HandlerMethod) {
			this.processTime = System.currentTimeMillis();
			this.sysLog.setAccessTime(new Date());
			this.sysLog.setHostName(request.getRemoteHost());
			this.sysLog.setIpAddress(request.getRemoteAddr());
			Authentication authentication = getContext().getAuthentication();
			if (authentication != null) {
				PubUser user = (PubUser) authentication.getPrincipal();
				this.sysLog.setLoginUser(user.getUserAccount());
			} else {
				this.sysLog.setLoginUser("游客");
			}
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Class<?> beanType = handlerMethod.getBeanType();
			Method method = handlerMethod.getMethod();
			String methodName = beanType.getCanonicalName() + "."
					+ method.getName();
			this.sysLog.setMethodName(methodName);
			if (StringUtils.hasText(request.getQueryString())) {
				this.sysLog.setQueryString(request.getQueryString());
			} else {
				Map<String, String[]> params = request.getParameterMap();
				StringBuilder sb = new StringBuilder();
				boolean first = true;
				for (Entry<String, String[]> en : params.entrySet()) {
					if (!first) {
						sb.append(",");
					}
					sb.append(en.getKey());
					sb.append(":");
					String[] v = en.getValue();
					if (v.length > 1) {
						sb.append(Arrays.toString(v));
					} else {
						sb.append(v[0]);
					}
					first = false;
				}
				this.sysLog.setQueryString(sb.toString());
			}
			this.sysLog.setRequestUri(request.getRequestURI());
			this.sysLog.setRequestUrl(request.getRequestURL().toString());
		}
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			if (ex != null) {
				this.sysLog.setExceptionInfo(ex.getMessage());
				this.sysLog.setProcessResult("出现异常，处理失败！");
			} else {
				this.sysLog.setProcessResult("处理成功！");
			}
			this.processTime = System.currentTimeMillis() - this.processTime;
			this.sysLog.setProcessTime(this.processTime);
			this.service.save(this.sysLog);
		}
	}
}
